#include "RadarPlot.h"
#include <iostream>
#include <qt4/QtGui/qpainter.h>
#include <cmath>

using namespace std;

RadarPlot::RadarPlot() {
    widget.setupUi(this);
    dAzimuth = -0.3*M_PI/180;
    step = 0;
    
    timer = new QTimer(this);
    connect(timer, SIGNAL(timeout()), this, SLOT(tick()));
    timer->start(24);
}

void RadarPlot::mousePressEvent(QMouseEvent* event) {
    cout << event->x() << "," << event->y() << endl;
    cout << "rozmiar buforu: " << dataBuffer->size() << endl;
}

void RadarPlot::resizeEvent(QResizeEvent*) {
    cacheImage = new QImage(width(), height(), QImage::Format_RGB32);
    cacheImage->fill(Qt::darkGreen);
    cachePainter = new QPainter(cacheImage);
    cachePainter->setRenderHint(QPainter::Antialiasing);
    cachePainter->setBrush(Qt::black);
    cachePainter->drawEllipse(0, 0 , width(), height());
}

void RadarPlot::paintEvent(QPaintEvent*) {
    QPainter painter(this);
    painter.setRenderHint(QPainter::Antialiasing);
    painter.setBrush(Qt::darkGreen);
    painter.drawImage(0, 0, *cacheImage);
    double angle = step*dAzimuth;       //kąt w radianach
    double angleDeg = angle*180/M_PI;   //kąt w stopniach
    painter.drawPie(0, 0, width(), height(), angleDeg*16, dAzimuth*180/M_PI*16);
    
    int x1 = width()/2 * sin(angle);
    int y1 = height()/2 * cos(angle);
    int radius = sqrt(x1*x1 + y1*y1);
    
    vector<complex<double> >* data = &dataBuffer->back();
    int scaleFactor = data->size()/radius;

    for(int r = 0; r < radius; r++) {
        int x = width()/2 + r*sin(angle+M_PI/2);
        int y = height()/2 + r*cos(angle+M_PI/2);
        
        complex<double> sectorValue = accumulate(data, r*scaleFactor, r*scaleFactor+scaleFactor-1);
//        cout << sectorValue.real() << ":" << sectorValue.imag() << endl;
        int colorNum = abs(sectorValue.real());
//        cout << colorNum << endl;
        cachePainter->setPen(QPen(QColor(colorNum, colorNum*10%255, colorNum)));
        cachePainter->drawPoint(x, y);
    }
    dataBuffer->pop_back();
}

complex<double> RadarPlot::accumulate(vector<complex<double> >* data, int from, int to) {
    complex<double> result(0,0);
    for(int i = from; i <= to; i++) {
        result += data->at(i);
    }
    return result;
}

void RadarPlot::setDataBuffer(boost::circular_buffer<std::vector<std::complex<double> > >* dataBuffer) {
    this->dataBuffer = dataBuffer;
}

void RadarPlot::setDAzimuth(double dAzimuth) {
    this->dAzimuth = dAzimuth;
}

void RadarPlot::tick() {
    //zerowanie licznika po pełnym obrocie "pałki"
//    if(step*dAzimuth == 2*M_PI) step = 0;
//    cout << step << endl;
    update();
    step++;
}

RadarPlot::~RadarPlot() {}
